# MIT License

# Copyright (c) 2025 Wufeng Song

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from lazyllm import pipeline
from openai import OpenAI
from flask import Flask, request, Response, send_from_directory
import json
import os

app = Flask(__name__)
client = OpenAI(
    api_key="d************************************1",
    base_url="https://api-mfr5n9z2q3r62eub.aistudio-app.com/v1"
)

def parse_requirements(input_data):
    product_type = input_data.get("product_type", "未知产品")
    scenario = input_data.get("scenario", "通用场景")
    style = input_data.get("style", "中性风格")
    keywords = input_data.get("keywords", [])
    count = input_data.get("count", 3)

    return f"""
    请生成{count}条{product_type}的创意文案，要求如下：
    - 应用场景：{scenario}
    - 风格：{style}
    - 必须包含关键词：{', '.join(keywords)}
    - 每条文案20-50字，语言生动有感染力
    - 不要在文案前添加序号，只返回文案内容
    - 每条文案单独占一行，不要添加任何解释说明
    """

def generate_copy(prompt):
    return client.chat.completions.create(
        model="qwen3:32b",
        messages=[{"role": "user", "content": prompt}],
        stream=True,
        temperature=0.8
    )

def format_copy(completion):
    full_content = []
    for chunk in completion:
        if chunk.choices[0].delta.content:
            full_content.append(chunk.choices[0].delta.content)
    full_text = ''.join(full_content)

    lines = [line.strip() for line in full_text.split('\n') if line.strip()]

    filtered = []
    for line in lines:
        has_numbering = line[0].isdigit() and (len(line) < 3 or line[1] in ['.', ')', '、'])

        explanation_words = ['文案', '说明', '示例', '以上', '总结', '共', '条']
        has_explanation = any(word in line for word in explanation_words)
        valid_length = 20 <= len(line) <= 50
        if not has_numbering and not has_explanation and valid_length:
            filtered.append(line)

    if len(filtered) < 1 and len(lines) > 0:
        for line in lines:
            if 20 <= len(line) <= 100 and not has_numbering and not has_explanation:
                chunks = [line[i:i + 50] for i in range(0, len(line), 50)]
                for chunk in chunks:
                    if 20 <= len(chunk):
                        filtered.append(chunk.strip())
                        if len(filtered) >= 3:
                            break
                if len(filtered) >= 3:
                    break

    return json.dumps({"copy_list": filtered}, ensure_ascii=False)

copy_pipeline = pipeline(parse_requirements, generate_copy, format_copy)

@app.route("/", methods=["GET"])
def serve_index():
    web_dir = os.path.join(os.path.dirname(__file__), "Web")
    return send_from_directory(web_dir, "index.html")

@app.route("/generate", methods=["POST"])
def generate_api():
    input_data = request.json
    result = copy_pipeline(input_data)
    return Response(result, mimetype="application/json")

if __name__ == "__main__":
    web_dir = os.path.join(os.path.dirname(__file__), "Web")
    if not os.path.exists(web_dir):
        os.makedirs(web_dir)
        print(f"已自动创建 Web 文件夹：{web_dir}，请将 index.html 放入该目录")
        exit()
    app.run(host="0.0.0.0", port=8080, debug=True)
    print("创意文案生成器已启动，访问 http://localhost:8080 开始使用")
